package com.jswlw.controller.admin.biz;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.jswlw.common.BaseException;
import com.jswlw.common.ResponseStatus;
import com.jswlw.common.utils.ExcelUtils;
import com.jswlw.controller.BaseController;
import com.jswlw.entity.biz.*;
import com.jswlw.service.biz.*;
import com.jswlw.service.helper.DevApiHelper;
import com.jswlw.web.manager.SessionAdminManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Slf4j
@Controller
@RequestMapping("/admin/biz/devInfo")
public class AdminDevInfoController extends BaseController {
    @Autowired
    DevInfoService service;
    @Autowired
    DevTypeService devTypeService;
    @Autowired
    DevFilterService devFilterService;
    @Autowired
    FilterInfoService filterInfoService;
    @Autowired
    DevApiHelper devApiHelper;
    @Autowired
    DistributorService distributorService;
    @Autowired
    DistributorAmountConsumeService distributorAmountConsumeService;
    @Autowired
    DevSetService devSetService;

    @RequestMapping("/index")
    public ModelAndView index() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("biz/devInfo/index");
        modelAndView.addObject("bindStatus", 1);
        modelAndView.addObject("devTypes", devTypeService.queryList(new DevType()));
        return modelAndView;
    }

    @RequestMapping("/indexNoBind")
    public ModelAndView indexNoBind() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("biz/devInfo/index");
        modelAndView.addObject("bindStatus", 0);
        modelAndView.addObject("devTypes", devTypeService.queryList(new DevType()));
        return modelAndView;
    }

    /**
     * 广告列表
     *
     * @param
     * @return
     */
    @RequestMapping("/list")
    @ResponseBody
    public Object list(@RequestBody DevInfo filter) {
        if (Objects.nonNull(SessionAdminManager.getCurrentUser().getDistributor())) {
            filter.setDistributorIds(SessionAdminManager.getCurrentUser().getDistributor().getChildrenIds());
        }
        Page<DevInfo> page = service.queryPage(filter, filter.getOffset(), filter.getLimit());
        List<DevInfo> list = new ArrayList<>();
        page.getResult().forEach(devInfo -> {
            Integer filterFlag = 0;
            for (DevFilter devFilter : devFilterService.find4DevId(devInfo.getId())) {
                if (devFilter.getMaxValue() - devFilter.getUsed() < 10) {
                    filterFlag = 1;
                }
            }
            DevInfo retDevInfo = service.find4Id(devInfo.getId());
            retDevInfo.setFilterFlag(filterFlag);
            list.add(retDevInfo);
        });
        return pageResult(list, page.getTotal());
    }


    /**
     * 新增广告
     *
     * @return
     */
    @RequestMapping("/add")
    public ModelAndView add() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("devTypes", devTypeService.queryList(new DevType()));
        modelAndView.setViewName("biz/devInfo/edit");
        return modelAndView;
    }

    /**
     * 编辑广告
     *
     * @param id
     * @return
     */
    @RequestMapping("/edit")
    public ModelAndView edit(String id) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("info", service.find4Id(id));
        modelAndView.setViewName("biz/devInfo/edit");
        return modelAndView;
    }

    @RequestMapping("/view")
    public ModelAndView view(String id) {
        ModelAndView modelAndView = new ModelAndView();
        DevInfo devInfo = service.find4Id(id);
        if (Objects.nonNull(devInfo.getDevTypeId())) {
            DevType devType = devTypeService.find4Id(devInfo.getDevTypeId());
            if (Objects.nonNull(devType)) {
                devInfo.setDevTypeName(devType.getName());
            }
        }


        DevFilter devFilter = new DevFilter();
        devFilter.setDevId(id);
        List<DevFilter> devFilters = devFilterService.queryList(devFilter);
        devFilters.forEach(filter -> {
            filter.setFilterInfo(filterInfoService.find4Id(filter.getFilterId()));
        });
        modelAndView.addObject("filters", devFilters);

        modelAndView.addObject("info", devInfo);

        modelAndView.addObject("devSet", devSetService.find4DevId(devInfo.getId()));
        modelAndView.setViewName("biz/devInfo/view");
        return modelAndView;
    }

    /**
     * 保存广告
     *
     * @param devInfo
     * @param
     * @return
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public ModelMap save(DevInfo devInfo) {
        try {
            if (devInfo.getId() == null) {
                service.add(devInfo);
            } else {
                service.update(devInfo);
            }
            return this.successResult(null);
        } catch (Exception e) {
            log.error("保存失败", e);
            return this.failResult("保存失败" + e.getMessage());
        }
    }

    /**
     * 删除广告
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ModelMap delete(Model model, String id) {
        try {
            service.delete(id);
            return this.successResult("删除成功");
        } catch (Exception e) {
            log.error("保存失败", e);
            return this.failResult("删除失败" + e.getMessage());
        }
    }

    @RequestMapping("/unBind")
    @ResponseBody
    public ModelMap unBind(String id) {
        try {
            service.unBind(id);
            return this.successResult("解绑成功");
        } catch (Exception e) {
            log.error("解绑失败", e);
            return this.failResult("解绑失败" + e.getMessage());
        }
    }

    @RequestMapping("/recharge/{id}/{amount}")
    @ResponseBody
    public ModelMap recharge(@PathVariable("id") String id, @PathVariable("amount") Integer amount) {
        try {
            DevInfo devInfo = service.find4Id(id);
            log.info(JSON.toJSONString(devInfo));
            if (devInfo.getOnlineStatus().equals(0)) {
                BaseException.sneakyThrows(ResponseStatus.BUSINESS_ERROR.getCode(), "设备不在线");
            }
            if (Objects.nonNull(SessionAdminManager.getCurrentUser().getDistributor())) {
                Distributor distributor = distributorService.find4Id(SessionAdminManager.getCurrentUser().getDistributor().getId());

                if (devInfo.getBillTypeId().equals(0)) {
                    if (distributor.getLl() < amount) {
                        BaseException.sneakyThrows(ResponseStatus.BUSINESS_ERROR.getCode(), "经销商流量不足");
                    }
                } else if (devInfo.getBillTypeId().equals(1)) {
                    if (distributor.getSc() < amount) {
                        BaseException.sneakyThrows(ResponseStatus.BUSINESS_ERROR.getCode(), "经销商时长不足");
                    }
                } else {
                    BaseException.sneakyThrows(ResponseStatus.BUSINESS_ERROR.getCode(), "卖断模式不允许充值");
                }
            }


            service.addMoney(id, amount);
            return this.successResult("充值成功");
        } catch (Exception e) {
            log.error("充值失败", e);
            return this.failResult("充值失败" + e.getMessage());
        }
    }

    @RequestMapping("/unRecharge/{id}/{amount}")
    @ResponseBody
    public ModelMap unRecharge(@PathVariable("id") String id, @PathVariable("amount") Integer amount) {
        try {
            DevInfo devInfo = service.find4Id(id);
            if (devInfo.getOnlineStatus().equals(0)) {
                BaseException.sneakyThrows(ResponseStatus.BUSINESS_ERROR.getCode(), "设备不在线");
            }
            service.subMoney(id, amount);
            return this.successResult("负充值成功");
        } catch (Exception e) {
            log.error("负充值失败", e);
            return this.failResult("负充值失败" + e.getMessage());
        }
    }

    @RequestMapping("/start")
    @ResponseBody
    public ModelMap start(String id) {
        try {
            service.start(id);
            return this.successResult("开机成功");
        } catch (Exception e) {
            log.error("开机失败", e);
            return this.failResult("开机失败" + e.getMessage());
        }
    }

    @RequestMapping("/stop")
    @ResponseBody
    public ModelMap stop(String id) {
        try {
            service.stop(id);
            return this.successResult("关机成功");
        } catch (Exception e) {
            log.error("关机失败", e);
            return this.failResult("关机失败" + e.getMessage());
        }
    }

    @RequestMapping("/force")
    @ResponseBody
    public ModelMap force(String id) {
        try {
            service.force(id);
            return this.successResult("强冲成功");
        } catch (Exception e) {
            log.error("强冲失败", e);
            return this.failResult("强冲失败" + e.getMessage());
        }
    }

    @RequestMapping("/filterInit/{id}")
    @ResponseBody
    public ModelMap filterInit(@PathVariable("id") Integer id) {
        DevFilter devFilter = devFilterService.find4Id(id);
        service.filterInit(devFilter.getDevId(), devFilter.getSort());
        return this.successResult("");
    }

    @RequestMapping("/devInit")
    @ResponseBody
    public ModelMap devInit(String id) {
        try {
            service.unBind(id);
            service.devInit(id);
            return this.successResult("恢复出厂成功");
        } catch (Exception e) {
            log.error("恢复出厂失败", e);
            return this.failResult("恢复出厂失败" + e.getMessage());
        }
    }

    @RequestMapping("/switchModel")
    @ResponseBody
    public ModelMap switchModel(@RequestParam(value = "devId", required = true) String devId,
                                @RequestParam(value = "billType", required = false) Integer billType,
                                @RequestParam(value = "ll2sc", required = false) Integer ll2sc,
                                @RequestParam(value = "dwbgzsj", required = false) Integer dwbgzsj,
                                @RequestParam(value = "qzcxsj", required = false) Integer qzcxsj,
                                @RequestParam(value = "dscxsj", required = false) Integer dscxsj,
                                @RequestParam(value = "jxsc", required = false) Integer jxsc,
                                @RequestParam(value = "oneWaterOfTime", required = false) Integer oneWaterOfTime) {
        try {
            DevInfo devInfo = service.find4Id(devId);
            if (devInfo.getOnlineStatus().equals(0)) {
                return this.failResult("操作失败设备不在线");
            }
            DevSet devSet = devSetService.find4DevId(devId);
            if (Objects.nonNull(billType)) {
                if (Objects.isNull(ll2sc)) {
                    BaseException.sneakyThrows(ResponseStatus.BUSINESS_ERROR.getCode(), "流量时长转换比例不允许为空");
                }
                devApiHelper.switchBillMode(devInfo.getImei(), ll2sc, billType.byteValue());
                devSet.setGzms(billType);
                devSet.setLl2sc(ll2sc);
            }
            if (Objects.nonNull(dwbgzsj)) {
                devApiHelper.rw_run_time(devInfo.getImei(), dwbgzsj.byteValue());
                devSet.setPumpWorkTime(dwbgzsj);
            }
            if (Objects.nonNull(qzcxsj)) {
                devApiHelper.modifyWashTime(devInfo.getImei(), qzcxsj.byteValue());
                devSet.setWashTime(qzcxsj);
            }
            if (Objects.nonNull(dscxsj)) {
                devApiHelper.modifyWashFixedTime(devInfo.getImei(), dscxsj.shortValue());
                devSet.setWashFixedTime(dscxsj);
            }

            if (Objects.nonNull(jxsc)) {
                devApiHelper.modifyServerTime(devInfo.getImei(), jxsc.byteValue());
                devSet.setServiceTime(jxsc);
            }
            if (Objects.nonNull(oneWaterOfTime)) {
                devApiHelper.rw_one_water_of_time(devInfo.getImei(), oneWaterOfTime.byteValue());
                devSet.setOneWaterOfTime(oneWaterOfTime);
            }
            devSetService.update(devSet);
            return this.successResult("操作成功");
        } catch (Exception e) {
            log.error("操作失败", e);
            return this.failResult("操作失败" + e.getMessage());
        }
    }

    /**
     * 导出设备信息
     */
    @RequestMapping(value = "/export")
    public @ResponseBody
    String export(HttpServletResponse response) {
        response.setContentType("application/binary;charset=UTF-8");
        try {
            ServletOutputStream out = response.getOutputStream();
            try {
                //设置文件头：最后一个参数是设置下载文件名(这里我们叫：张三.pdf)
                response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode("设备信息.xls", "UTF-8"));
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }

            String[] titles = {"设备id", "设备别名", "用户名", "电话", "地址", "代理商id", "代理商名称", "模式", "imei"};
            DevInfo filter = new DevInfo();
            filter.setBindStatus(1);
            List<DevInfo> devInfoList = service.queryList(filter);
            ExcelUtils.exportDevInfo(titles, devInfoList, out);
            return "success" ;
        } catch (Exception e) {
            e.printStackTrace();
            return "导出信息失败" ;
        }
    }

    @RequestMapping("/read/{id}/{type}")
    @ResponseBody
    public ModelMap read(@PathVariable("id") String id, @PathVariable("type") Integer type) {
        DevInfo devInfo = service.find4Id(id);
        DevSet devSet = devSetService.find4DevId(devInfo.getId());
        if (devInfo.getOnlineStatus().equals(0)) {
            throw BaseException.of(ResponseStatus.BUSINESS_ERROR.getCode(), "设备不在线");
        }
        Integer value = 0;
        switch (type) {
            case 1:
                value = 0;
                break;
            case 2:
                value = devApiHelper.rw_run_time(devInfo.getImei(), (short) 0);
                devSet.setPumpWorkTime(value);
                break;
            case 3:
                value = devApiHelper.modifyWashTime(devInfo.getImei(), (short) 0);
                devSet.setWashTime(value);
                break;
            case 4:
                value = devApiHelper.modifyWashFixedTime(devInfo.getImei(), (short) 0);
                devSet.setWashFixedTime(value);
                break;
            case 5:
                value = devApiHelper.modifyServerTime(devInfo.getImei(), (short) 0);
                devSet.setServiceTime(value);
                break;
            case 6:
                value = devApiHelper.rw_one_water_of_time(devInfo.getImei(), (short) 0);
                devSet.setOneWaterOfTime(value);
                break;
            default:
        }
        //devSetService.update(devSet);

        return this.successResult(value);
    }
}
